<template>
    <div
        class="flex h-screen bg-gray-50 overflow-hidden"
        style="height: calc(100vh - 84px)"
    >
        <!-- 左侧文件预览区域 -->
        <div
            class="w-1/3 bg-white shadow-md flex flex-col transition-all duration-300 ease-in-out border-r border-gray-200"
        >
            <!-- 顶部：文件信息 + 类型切换 -->
            <div
                class="p-4 border-b border-gray-200 bg-gray-50 flex items-center justify-between"
            >
                <div class="flex items-center">
                    <div
                        class="w-10 h-10 rounded-md flex items-center justify-center mr-3"
                        :class="fileTypeIconClass"
                    >
                        <el-icon :size="24" class="text-white">
                            <component :is="fileTypeIcon" />
                        </el-icon>
                    </div>
                    <span
                        class="text-sm font-medium text-gray-800 truncate max-w-[180px]"
                        >{{ fileName }}</span
                    >
                </div>
                <!-- <el-select
                    v-model="fileType"
                    size="small"
                    placeholder="文件类型"
                    @change="handleFileTypeChange"
                    style="width: 140px"
                >
                    <el-option label="PDF" value="pdf" />
                    <el-option label="Word" value="word" />
                    <el-option label="Excel" value="excel" />
                    <el-option label="图片" value="image" />
                </el-select> -->
            </div>

            <!-- 核心预览内容区 -->
            <div class="flex-1 overflow-auto p-1 bg-gray-50">
                <!-- 加载状态 -->
                <div
                    v-if="loading"
                    class="w-full h-full flex flex-col items-center justify-center text-gray-500 p-6"
                >
                    <p>正在加载 {{ fileTypeText }} 文件...</p>
                    <p class="text-xs mt-1" v-if="loadingProgress > 0">
                        已加载 {{ Math.round(loadingProgress) }}%
                    </p>
                </div>

                <!-- 错误状态 -->
                <div
                    v-if="error && !loading"
                    class="w-full h-full flex flex-col items-center justify-center text-red-500 p-6"
                >
                    <el-icon size="40" class="mb-3"><WarningFilled /></el-icon>
                    <p class="text-center">{{ errorMessage }}</p>
                    <el-button
                        size="small"
                        class="mt-4 text-gray-700"
                        @click="reloadPreview"
                        >重新加载</el-button
                    >
                </div>

                <!-- PDF预览 -->
                <div
                    v-if="fileType === 'pdf' && !loading && !error"
                    class="w-full h-full flex flex-col"
                >
                    <div
                        id="pdfContainer"
                        class="flex-1 overflow-auto p-4 bg-white m-1 rounded shadow-sm"
                    >
                        <div id="pdfViewer" class="w-full"></div>
                    </div>
                    <!-- PDF控制栏 -->
                    <div
                        class="p-2 bg-gray-50 border-t border-gray-200 flex items-center justify-between"
                    >
                        <div class="flex items-center space-x-2">
                            <el-button
                                size="small"
                                @click="prevPdfPage"
                                :disabled="currentPdfPage <= 1"
                                icon="ArrowLeft"
                            />
                            <span class="text-xs text-gray-600"
                                >第 {{ currentPdfPage }} /
                                {{ totalPdfPages }} 页</span
                            >
                            <el-button
                                size="small"
                                @click="nextPdfPage"
                                :disabled="currentPdfPage >= totalPdfPages"
                                icon="ArrowRight"
                            />
                        </div>
                        <div class="flex items-center space-x-2">
                            <el-button
                                size="small"
                                @click="zoomOutPdf"
                                icon="ZoomOut"
                            />
                            <span class="text-xs text-gray-600"
                                >{{ Math.round(pdfZoom * 100) }}%</span
                            >
                            <el-button
                                size="small"
                                @click="zoomInPdf"
                                icon="ZoomIn"
                            />
                        </div>
                    </div>
                </div>

                <!-- Word预览 -->
                <div
                    v-if="fileType === 'word' && !loading && !error"
                    class="w-full h-full"
                >
                    <div
                        class="bg-white m-1 rounded shadow-sm overflow-auto h-full"
                    >
                        <div id="wordViewer" class="p-6 prose max-w-none">
                            <h1>文档标题示例</h1>
                            <p>
                                这是Word文档预览区域，实际场景将渲染解析后的文档内容
                            </p>
                            <h2>章节标题</h2>
                            <p>
                                包含格式化文本、列表、表格等Word原生元素的预览效果
                            </p>
                            <ul>
                                <li>列表项 1</li>
                                <li>列表项 2</li>
                                <li>列表项 3</li>
                            </ul>
                            <table
                                class="border-collapse border border-gray-300 w-full"
                            >
                                <tr>
                                    <th
                                        class="border border-gray-300 p-2 bg-gray-50"
                                    >
                                        表头1
                                    </th>
                                    <th
                                        class="border border-gray-300 p-2 bg-gray-50"
                                    >
                                        表头2
                                    </th>
                                </tr>
                                <tr>
                                    <td class="border border-gray-300 p-2">
                                        单元格1
                                    </td>
                                    <td class="border border-gray-300 p-2">
                                        单元格2
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Excel预览 -->
                <div
                    v-if="fileType === 'excel' && !loading && !error"
                    class="w-full h-full p-1"
                >
                    <div
                        class="bg-white rounded shadow-sm overflow-hidden h-full flex flex-col"
                    >
                        <div
                            class="bg-gray-50 border-b border-gray-200 px-2 py-1 flex items-center space-x-1 overflow-x-auto"
                        >
                            <div
                                class="px-3 py-1 text-xs bg-white border border-gray-200 border-b-0 rounded-t-md font-medium"
                            >
                                工作表1
                            </div>
                            <div
                                class="px-3 py-1 text-xs text-gray-600 hover:bg-gray-100 cursor-pointer"
                            >
                                工作表2
                            </div>
                            <div
                                class="px-3 py-1 text-xs text-gray-600 hover:bg-gray-100 cursor-pointer"
                            >
                                工作表3
                            </div>
                        </div>
                        <div class="flex-1 overflow-auto">
                            <el-table
                                :data="excelData"
                                border
                                stripe
                                class="w-full text-xs"
                                size="mini"
                                max-height="calc(100vh - 200px)"
                            >
                                <el-table-column
                                    v-for="(col, index) in excelColumns"
                                    :key="index"
                                    :prop="col.prop"
                                    :label="col.label"
                                    :width="col.width || 100"
                                    :align="col.align || 'left'"
                                />
                            </el-table>
                        </div>
                    </div>
                </div>

                <!-- 图片预览 -->
                <div
                    v-if="fileType === 'image' && !loading && !error"
                    class="w-full h-full flex items-center justify-center p-4 bg-gray-100"
                >
                    <div class="relative max-w-full max-h-full">
                        <img
                            :src="imageUrl"
                            alt="预览图片"
                            class="max-w-full max-h-[calc(100vh-180px)] object-contain shadow-md transition-all duration-300 z-0"
                            :style="{
                                transform: `scale(${imageZoom}) rotate(${imageRotation}deg)`,
                                cursor: 'grab',
                            }"
                            @load="imageLoaded"
                            @mousedown="
                                (e) => (e.target.style.cursor = 'grabbing')
                            "
                            @mouseup="(e) => (e.target.style.cursor = 'grab')"
                            @mouseleave="
                                (e) => (e.target.style.cursor = 'grab')
                            "
                        />
                    </div>
                    <!-- 图片控制栏 -->
                    <div
                        class="absolute bottom-4 left-1/2 transform -translate-x-1/2 bg-black bg-opacity-70 text-white rounded-full px-4 py-2 flex items-center space-x-4 z-999"
                    >
                        <el-button
                            size="small"
                            @click="zoomOutImage"
                            icon="ZoomOut"
                            class="text-white hover:bg-white/20"
                        />
                        <span class="text-xs"
                            >{{ Math.round(imageZoom * 100) }}%</span
                        >
                        <el-button
                            size="small"
                            @click="zoomInImage"
                            icon="ZoomIn"
                            class="text-white hover:bg-white/20"
                        />
                        <el-button
                            size="small"
                            @click="rotateImage"
                            icon="RefreshRight"
                            class="text-white hover:bg-white/20"
                        />
                        <el-button
                            size="small"
                            @click="resetImageTransform"
                            icon="Refresh"
                            class="text-white hover:bg-white/20"
                        />
                    </div>
                </div>
            </div>
        </div>

        <!-- 右侧解析内容区域（优化版） -->
        <div
            class="w-2/3 overflow-auto bg-gray-50 transition-all duration-300 ease-in-out"
        >
            <div class="p-4 max-w-full mx-auto">
                <!-- 文件信息卡片 -->
                <div
                    class="bg-white rounded-lg shadow-sm p-5 mb-5 border border-gray-200"
                >
                    <div
                        class="flex flex-col md:flex-row md:items-center justify-between mb-4 pb-4 border-b border-gray-100"
                    >
                        <div class="flex items-center">
                            <p class="text-gray-500">文件名：</p>
                            <p style="font-weight: 900">
                                {{ fileName }}
                            </p>
                        </div>
                        <el-button
                            type="primary"
                            class="mt-3 md:mt-0 bg-blue-600 hover:bg-blue-700 text-white"
                        >
                            <el-icon class="mr-1"><RefreshLeft /></el-icon
                            >重新解析
                        </el-button>
                    </div>

                    <!-- 统计信息网格（优化响应式） -->
                    <div
                        class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 text-sm"
                    >
                        <div
                            class="p-4 bg-blue-50 rounded-lg border border-blue-100 hover:shadow-md transition-shadow duration-200"
                        >
                            <div class="flex items-center mb-2">
                                <el-icon class="text-blue-500 mr-2"
                                    ><Clock
                                /></el-icon>
                                <p class="text-gray-500">运行时长</p>
                            </div>
                            <p class="text-gray-800 font-semibold">4min58s</p>
                        </div>
                        <div
                            class="p-4 bg-green-50 rounded-lg border border-green-100 hover:shadow-md transition-shadow duration-200"
                        >
                            <div class="flex items-center mb-2">
                                <el-icon class="text-green-500 mr-2"
                                    ><Calendar
                                /></el-icon>
                                <p class="text-gray-500">执行时间</p>
                            </div>
                            <p class="text-gray-800 font-semibold">
                                2025-09-04 17:32:38
                            </p>
                        </div>
                        <div
                            class="p-4 bg-purple-50 rounded-lg border border-purple-100 hover:shadow-md transition-shadow duration-200"
                        >
                            <div class="flex items-center mb-2">
                                <p class="text-gray-500">识别结果</p>
                            </div>
                            <p class="text-gray-800 font-semibold">
                                共提取164条记录
                            </p>
                            <p class="text-xs text-gray-600">
                                完整识别143条(87.2%)
                            </p>
                        </div>
                        <div
                            class="p-4 bg-amber-50 rounded-lg border border-amber-100 hover:shadow-md transition-shadow duration-200"
                        >
                            <div class="flex items-center mb-2">
                                <el-icon class="text-amber-500 mr-2"
                                    ><Money
                                /></el-icon>
                                <p class="text-gray-500">增值税信息</p>
                            </div>
                            <p class="text-gray-800 font-semibold">
                                总价（含税价）：2,477,650.26 元
                            </p>
                            <p class="text-xs text-gray-600">
                                不含税价：2,273,073.63元 | 税率：9%
                            </p>
                        </div>
                    </div>
                </div>

                <!-- 搜索和筛选区域（优化布局） -->
                <div
                    class="bg-white rounded-lg shadow-sm p-5 mb-5 border border-gray-200"
                >
                    <div class="flex flex-col md:flex-row gap-3 mb-3">
                        <el-input
                            placeholder="请输入工程名称、单项工程或分部分项"
                            size="default"
                            class="flex-1"
                        />
                        <el-select
                            placeholder="选择单位工程"
                            size="default"
                            class="w-full md:w-auto md:flex-1"
                        >
                            <el-option label="全部" value="" />
                            <el-option label="装饰工程" value="装饰工程" />
                            <el-option label="土建工程" value="土建工程" />
                            <el-option label="安装工程" value="安装工程" />
                        </el-select>
                        <el-select
                            placeholder="选择分部分项"
                            size="default"
                            class="w-full md:w-auto md:flex-1"
                        >
                            <el-option label="全部" value="" />
                            <el-option label="拆除" value="拆除" />
                            <el-option label="新建" value="新建" />
                            <el-option label="修缮" value="修缮" />
                        </el-select>
                    </div>

                    <div class="flex flex-wrap gap-2">
                        <el-button
                            type="primary"
                            class="bg-blue-600 hover:bg-blue-700 text-white"
                        >
                            <el-icon class="mr-1"><Search /></el-icon>搜索
                        </el-button>
                        <el-button
                            class="border-gray-300 text-gray-700 hover:bg-gray-100"
                        >
                            <el-icon class="mr-1"><Refresh /></el-icon>重置
                        </el-button>
                        <el-button
                            class="border-gray-300 text-gray-700 hover:bg-gray-100"
                        >
                            <el-icon class="mr-1"><Download /></el-icon>导出选中
                        </el-button>
                    </div>
                </div>

                <!-- 数据统计摘要（优化间距） -->
                <div
                    class="flex flex-wrap items-center justify-between mb-4 text-sm gap-2"
                >
                    <div class="flex items-center space-x-4">
                        <div class="flex items-center">
                            <span class="text-gray-500 mr-2">总条数：</span>
                            <span class="font-semibold text-gray-800">164</span>
                        </div>
                        <div class="flex items-center">
                            <span class="text-gray-500 mr-2">总合价：</span>
                            <span class="font-semibold text-green-600"
                                >¥ 2,477,650.26</span
                            >
                        </div>
                    </div>
                    <div class="flex items-center space-x-2">
                        <el-button
                            size="small"
                            class="border border-blue-200 text-blue-600 bg-blue-50 hover:bg-blue-100"
                            @click="expandAll"
                        >
                            全部展开
                        </el-button>
                        <el-button
                            size="small"
                            class="border border-blue-200 text-blue-600 bg-blue-50 hover:bg-blue-100"
                            @click="collapseAll"
                        >
                            全部折叠
                        </el-button>
                    </div>
                </div>

                <!-- 右侧表格区域（优化样式） -->
                <div
                    class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden"
                >
                    <el-table
                        :data="tableData"
                        border
                        stripe
                        highlight-current-row
                        class="w-full text-sm"
                        :row-class-name="tableRowClassName"
                        :expand-row-keys="expandedRows"
                        row-key="code"
                        :header-cell-style="{
                            background: '#f5f7fa',
                            color: '#4e5969',
                            fontWeight: 500,
                            padding: '10px 8px',
                        }"
                        :cell-style="{ padding: '10px 8px' }"
                    >
                        <el-table-column type="selection" width="50" />
                        <el-table-column type="expand">
                            <template #default="scope">
                                <div class="p-3 bg-gray-50 rounded-lg text-sm">
                                    <div
                                        class="grid grid-cols-1 md:grid-cols-2 gap-2"
                                    >
                                        <div>
                                            <p class="text-gray-500">
                                                详细特征描述：
                                            </p>
                                            <p class="text-gray-700 mt-1">
                                                {{
                                                    scope.row.detailDescription
                                                }}
                                            </p>
                                        </div>
                                        <div>
                                            <p class="text-gray-500">
                                                计算说明：
                                            </p>
                                            <p class="text-gray-700 mt-1">
                                                {{ scope.row.calculationNote }}
                                            </p>
                                        </div>
                                    </div>
                                    <div
                                        class="mt-2 pt-2 border-t border-gray-200"
                                    >
                                        <p class="text-gray-500">识别状态：</p>
                                        <el-tag
                                            :type="
                                                scope.row.recognitionStatus ===
                                                '完整'
                                                    ? 'success'
                                                    : 'warning'
                                            "
                                            size="small"
                                            class="mt-1"
                                        >
                                            {{ scope.row.recognitionStatus }}
                                        </el-tag>
                                        <span
                                            v-if="
                                                scope.row.recognitionStatus !==
                                                '完整'
                                            "
                                            class="text-amber-600 text-xs ml-2"
                                        >
                                            {{ scope.row.recognitionNote }}
                                        </span>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="unitProject"
                            label="单位工程"
                            width="140"
                        />
                        <el-table-column
                            prop="subProject"
                            label="分部分项"
                            width="120"
                        />
                        <el-table-column prop="code" label="编码" width="120" />
                        <el-table-column
                            prop="name"
                            label="名称"
                            min-width="140"
                        >
                            <template #default="scope">
                                <span
                                    :class="
                                        scope.row.highlight
                                            ? 'font-medium text-blue-700'
                                            : ''
                                    "
                                >
                                    {{ scope.row.name }}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="featureDesc"
                            label="项目特征描述"
                            min-width="200"
                        />
                        <el-table-column
                            prop="measurementUnit"
                            label="计量单位"
                            width="90"
                            align="center"
                        />
                        <el-table-column
                            prop="quantity"
                            label="工程量"
                            width="100"
                            align="right"
                        />
                        <el-table-column
                            prop="comprehensivePrice"
                            label="综合单价"
                            width="110"
                            align="right"
                        >
                            <template #default="scope"
                                >¥ {{ scope.row.comprehensivePrice }}</template
                            >
                        </el-table-column>
                        <el-table-column
                            prop="totalPrice"
                            label="合价"
                            width="110"
                            align="right"
                        >
                            <template #default="scope">
                                <span class="font-medium text-gray-800"
                                    >¥ {{ scope.row.totalPrice }}</span
                                >
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="80" align="center">
                            <template #default="scope">
                                <el-button
                                    size="small"
                                    icon="Edit"
                                    class="text-blue-600 hover:text-blue-800 hover:bg-blue-50 p-1"
                                />
                            </template>
                        </el-table-column>
                    </el-table>

                    <!-- 分页（优化响应式） -->
                    <div class="p-4 border-t border-gray-200 bg-gray-50">
                        <div
                            class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3"
                        >
                            <div class="text-sm text-gray-500">
                                显示
                                <span class="font-medium text-gray-800">{{
                                    (currentPage - 1) * pageSize + 1
                                }}</span>
                                到
                                <span class="font-medium text-gray-800">{{
                                    Math.min(currentPage * pageSize, 164)
                                }}</span>
                                条，共
                                <span class="font-medium text-gray-800"
                                    >164</span
                                >
                                条记录
                            </div>

                            <el-pagination
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                                :current-page="currentPage"
                                :page-sizes="[10, 20, 50]"
                                :page-size="pageSize"
                                layout="sizes, prev, pager, next, jumper"
                                :total="164"
                                class="flex items-center"
                            />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from "vue";
import * as pdfjsLib from "pdfjs-dist";
import "pdfjs-dist/build/pdf.worker.entry";
import "pdfjs-dist/web/pdf_viewer.css";

// 核心图标（仅保留使用到的）
import {
    Files,
    Document,
    DataBoard,
    Picture,
    WarningFilled,
    ArrowLeft,
    ArrowRight,
    ZoomIn,
    ZoomOut,
    RefreshRight,
    Refresh,
    Clock,
    Calendar,
    Money,
    Search,
    RefreshLeft,
    Edit,
    Loading,
} from "@element-plus/icons-vue";
import { useRoute } from "vue-router";
const route = useRoute();
// -------------------------- 核心状态管理 --------------------------
const fileType = ref("pdf"); // 切换类型：pdf/word/excel/image
const { label } = route.query;
const fileName = ref(label);

// 加载/错误状态
const loading = ref(false);
const loadingProgress = ref(0);
const error = ref(false);
const errorMessage = ref("");

// -------------------------- 各类型预览状态 --------------------------
// PDF状态
const currentPdfPage = ref(1);
const totalPdfPages = ref(0);
const pdfZoom = ref(1.0);
let pdfDoc = null; // PDF实例

// Excel预览数据
const excelColumns = ref([
    { label: "行号", prop: "rowNum", width: 60, align: "center" },
    { label: "编码", prop: "code", width: 120 },
    { label: "名称", prop: "name", width: 180 },
    { label: "工程量", prop: "quantity", width: 100, align: "right" },
    {
        label: "综合单价",
        prop: "comprehensivePrice",
        width: 120,
        align: "right",
    },
    { label: "合价", prop: "totalPrice", width: 120, align: "right" },
    { label: "备注", prop: "remark", width: 150 },
]);
const excelData = ref([
    {
        rowNum: 1,
        code: "011605001003",
        name: "平面块料拆除",
        quantity: "93.43",
        comprehensivePrice: "14.59",
        totalPrice: "1,400.52",
        remark: "装饰工程-拆除",
    },
    {
        rowNum: 2,
        code: "011605002003",
        name: "立面块料拆除",
        quantity: "355.60",
        comprehensivePrice: "11.03",
        totalPrice: "3,702.66",
        remark: "装饰工程-拆除",
    },
    {
        rowNum: 3,
        code: "011608001001",
        name: "门窗拆除",
        quantity: "12.00",
        comprehensivePrice: "85.20",
        totalPrice: "1,022.40",
        remark: "装饰工程-拆除",
    },
    {
        rowNum: 4,
        code: "011608002002",
        name: "金属窗拆除",
        quantity: "8.00",
        comprehensivePrice: "62.50",
        totalPrice: "500.00",
        remark: "装饰工程-拆除",
    },
    {
        rowNum: 5,
        code: "011609001001",
        name: "混凝土构件拆除",
        quantity: "15.75",
        comprehensivePrice: "320.80",
        totalPrice: "5,052.60",
        remark: "土建工程-拆除",
    },
    {
        rowNum: 6,
        code: "010801001001",
        name: "镀锌钢管",
        quantity: "85.60",
        comprehensivePrice: "65.20",
        totalPrice: "5,581.12",
        remark: "安装工程-新建",
    },
    {
        rowNum: 7,
        code: "010901001001",
        name: "消火栓",
        quantity: "4.00",
        comprehensivePrice: "860.50",
        totalPrice: "3,442.00",
        remark: "安装工程-新建",
    },
]);

// 图片预览状态
const imageUrl = ref("https://picsum.photos/800/600?random=1");
const imageZoom = ref(1.0);
const imageRotation = ref(0);

// 右侧表格状态
const tableData = ref([
    {
        unitProject: "装饰工程",
        subProject: "拆除",
        code: "011605001003",
        name: "平面块料拆除",
        featureDesc: "饰面板种类：陶瓷锦砖，基层类型：墙面",
        measurementUnit: "m2",
        quantity: "93.43",
        comprehensivePrice: "14.59",
        totalPrice: "1,400.52",
        highlight: true,
        recognitionStatus: "完整",
        recognitionNote: "",
        detailDescription:
            "1. 拆除部位：室内墙面；2. 拆除方式：人工拆除；3. 废料清理：包含场内运输20m内；4. 饰面板厚度：约10mm",
        calculationNote: "工程量按实际测量面积计算，扣除门窗洞口面积",
    },
    {
        unitProject: "装饰工程",
        subProject: "拆除",
        code: "011605002003",
        name: "立面块料拆除",
        featureDesc: "饰面板种类：大理石，基层类型：墙面",
        measurementUnit: "m2",
        quantity: "355.60",
        comprehensivePrice: "11.03",
        totalPrice: "3,702.66",
        highlight: false,
        recognitionStatus: "完整",
        recognitionNote: "",
        detailDescription:
            "1. 拆除部位：室外墙面；2. 拆除方式：人工拆除；3. 废料清理：包含场内运输20m内；4. 大理石厚度：约20mm",
        calculationNote: "工程量按实际测量面积计算，包含附墙柱展开面积",
    },
    {
        unitProject: "装饰工程",
        subProject: "拆除",
        code: "011608001001",
        name: "门窗拆除",
        featureDesc: "门类型：木质门，开启方式：平开",
        measurementUnit: "樘",
        quantity: "12.00",
        comprehensivePrice: "85.20",
        totalPrice: "1,022.40",
        highlight: false,
        recognitionStatus: "不完整",
        recognitionNote: "缺少门框材质信息",
        detailDescription:
            "1. 门规格：900×2100mm；2. 拆除方式：人工拆除；3. 包含门框及五金件拆除",
        calculationNote: "按实际数量清点计算",
    },
    {
        unitProject: "土建工程",
        subProject: "拆除",
        code: "011609001001",
        name: "混凝土构件拆除",
        featureDesc: "构件名称：混凝土梁",
        measurementUnit: "m3",
        quantity: "15.75",
        comprehensivePrice: "320.80",
        totalPrice: "5,052.60",
        highlight: true,
        recognitionStatus: "不完整",
        recognitionNote: "混凝土强度等级未明确",
        detailDescription:
            "1. 构件规格：300×500mm；2. 拆除方式：机械辅助人工拆除；3. 废料处理：破碎后外运",
        calculationNote: "按构件实际体积计算，包含梁长按图示尺寸",
    },
]);
const currentPage = ref(1);
const pageSize = ref(10);
const expandedRows = ref([]);

// -------------------------- 计算属性 --------------------------
// 文件类型图标与样式
const fileTypeIcon = computed(() => {
    const iconMap = {
        pdf: Files,
        word: Document,
        excel: DataBoard,
        image: Picture,
    };
    return iconMap[fileType.value] || Files;
});
const fileTypeIconClass = computed(() => {
    const classMap = {
        pdf: "bg-red-500",
        word: "bg-blue-500",
        excel: "bg-green-500",
        image: "bg-purple-500",
    };
    return classMap[fileType.value] || "bg-gray-500";
});
const fileTypeText = computed(() => {
    const textMap = { pdf: "PDF", word: "Word", excel: "Excel", image: "图片" };
    return textMap[fileType.value] || "文件";
});

// -------------------------- 核心方法 --------------------------
/**
 * 统一初始化文件预览
 */
const initFilePreview = async () => {
    // 重置状态
    loading.value = true;
    error.value = false;
    loadingProgress.value = 0;

    try {
        // 模拟加载进度
        const progressTimer = setInterval(() => {
            if (loadingProgress.value < 90) {
                loadingProgress.value += Math.min(
                    Math.random() * 15,
                    90 - loadingProgress.value
                );
            }
        }, 200);

        // 按类型初始化
        const initMap = {
            pdf: initPdfPreview,
            word: initWordPreview,
            excel: initExcelPreview,
            image: initImagePreview,
        };
        await (initMap[fileType.value] || (() => Promise.resolve()))();

        // 完成加载
        clearInterval(progressTimer);
        loadingProgress.value = 100;
        loading.value = false;
    } catch (err) {
        console.error(`[${fileTypeText.value}]预览初始化失败:`, err);
        error.value = true;
        errorMessage.value =
            err.message ||
            `无法加载${fileTypeText.value}文件，请检查文件有效性`;
        loading.value = false;
    }
};

/**
 * PDF预览初始化
 */
const initPdfPreview = async () => {
    // 销毁旧实例
    if (pdfDoc) {
        pdfDoc.destroy();
        pdfDoc = null;
    }

    // 清空容器
    const pdfViewer = document.getElementById("pdfViewer");
    if (pdfViewer) pdfViewer.innerHTML = "";

    try {
        // 加载PDF
        const loadingTask = pdfjsLib.getDocument({
            url: "https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/examples/learning/helloworld.pdf",
            cMapUrl: "https://unpkg.com/pdfjs-dist@3.4.120/cmaps/",
            cMapPacked: true,
            onProgress: (progressData) => {
                loadingProgress.value = Math.round(
                    (progressData.loaded / progressData.total) * 100
                );
            },
        });

        pdfDoc = await loadingTask.promise;
        totalPdfPages.value = pdfDoc.numPages;
        currentPdfPage.value = 1;

        // 渲染第一页
        await renderPdfPage(currentPdfPage.value);
    } catch (err) {
        throw new Error("PDF加载失败: " + (err.message || "未知错误"));
    }
};

/**
 * 渲染PDF页面
 */
const renderPdfPage = async (pageNum) => {
    if (!pdfDoc) return;

    try {
        const page = await pdfDoc.getPage(pageNum);
        const viewport = page.getViewport({ scale: pdfZoom.value });
        const pdfViewer = document.getElementById("pdfViewer");
        if (!pdfViewer) return;

        // 创建canvas
        const canvas = document.createElement("canvas");
        canvas.className =
            "pdf-page mx-auto border border-gray-100 mb-4 shadow-sm";
        const ctx = canvas.getContext("2d");
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        // 清空容器并添加新canvas
        pdfViewer.innerHTML = "";
        pdfViewer.appendChild(canvas);

        // 渲染页面
        const renderContext = { canvasContext: ctx, viewport: viewport };
        await page.render(renderContext).promise;

        // 强制重绘
        pdfViewer.style.display = "none";
        pdfViewer.offsetHeight;
        pdfViewer.style.display = "block";
    } catch (err) {
        throw new Error("PDF页面渲染失败");
    }
};

/**
 * Word预览初始化
 */
const initWordPreview = async () => {
    await new Promise((resolve) => setTimeout(resolve, 600)); // 模拟加载
};

/**
 * Excel预览初始化
 */
const initExcelPreview = async () => {
    await new Promise((resolve) => setTimeout(resolve, 500)); // 模拟加载
};

/**
 * 图片预览初始化
 */
const initImagePreview = async () => {
    imageZoom.value = 1.0;
    imageRotation.value = 0;
    await new Promise((resolve) => setTimeout(resolve, 500)); // 模拟加载
};

// -------------------------- 交互方法 --------------------------
// PDF交互
const prevPdfPage = async () => {
    if (currentPdfPage.value > 1) {
        currentPdfPage.value--;
        await renderPdfPage(currentPdfPage.value);
    }
};
const nextPdfPage = async () => {
    if (currentPdfPage.value < totalPdfPages.value) {
        currentPdfPage.value++;
        await renderPdfPage(currentPdfPage.value);
    }
};
const zoomInPdf = async () => {
    if (pdfZoom.value < 2.0) {
        pdfZoom.value = Math.round((pdfZoom.value + 0.1) * 10) / 10;
        await renderPdfPage(currentPdfPage.value);
    }
};
const zoomOutPdf = async () => {
    if (pdfZoom.value > 0.5) {
        pdfZoom.value = Math.round((pdfZoom.value - 0.1) * 10) / 10;
        await renderPdfPage(currentPdfPage.value);
    }
};

// 图片交互
const zoomInImage = () =>
    imageZoom.value < 3.0 &&
    (imageZoom.value = Math.round((imageZoom.value + 0.1) * 10) / 10);
const zoomOutImage = () =>
    imageZoom.value > 0.3 &&
    (imageZoom.value = Math.round((imageZoom.value - 0.1) * 10) / 10);
const rotateImage = () =>
    (imageRotation.value = (imageRotation.value + 90) % 360);
const resetImageTransform = () => {
    imageZoom.value = 1.0;
    imageRotation.value = 0;
};
const imageLoaded = () => {}; // 简化空方法

// 文件类型切换
const handleFileTypeChange = (type) => {
    fileType.value = type;
    initFilePreview();
};
// 重新加载预览
const reloadPreview = () => initFilePreview();

// 右侧表格方法
const handleSizeChange = (val) => {
    pageSize.value = val;
    currentPage.value = 1;
};
const handleCurrentChange = (val) => (currentPage.value = val);
const expandAll = () =>
    (expandedRows.value = tableData.value.map((row) => row.code));
const collapseAll = () => (expandedRows.value = []);
const tableRowClassName = ({ row }) =>
    row.recognitionStatus !== "完整" ? "bg-amber-50/50" : "";

// -------------------------- 生命周期 --------------------------
onMounted(() => {
    initFilePreview();
});
onUnmounted(() => {
    // 销毁PDF实例，避免内存泄漏
    if (pdfDoc) pdfDoc.destroy();
});
</script>

<style scoped>
/* 基础组件样式优化 */
::v-deep .el-button--small {
    padding: 2px 6px !important;
    font-size: 12px !important;
}
::v-deep .el-button--small .el-icon {
    vertical-align: middle;
    font-size: 14px !important;
}

/* 表格样式优化 */
::v-deep .el-table__row:hover > td {
    background-color: #f0f7ff !important;
    transition: background-color 0.2s ease;
}
::v-deep .el-table__row.current-row > td {
    background-color: #e6f7ff !important;
    font-weight: 500;
}
::v-deep .el-table th,
::v-deep .el-table td {
    border-right: 1px solid #f0f0f0;
}

/* 预览区域样式 */
.pdf-page {
    transition: all 0.2s ease;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    display: block !important;
}
#pdfViewer {
    min-height: 300px;
    display: flex;
    flex-direction: column;
    align-items: center;
}
#wordViewer {
    line-height: 1.6;
}
#wordViewer h1,
#wordViewer h2 {
    color: #1f2937;
    margin-bottom: 0.75rem;
}
#wordViewer p,
#wordViewer ul,
#wordViewer table {
    color: #4b5563;
    margin-bottom: 0.75rem;
}

/* 滚动条优化 */
#pdfContainer,
::v-deep .el-table__body-wrapper {
    scrollbar-width: thin;
}
#pdfContainer::-webkit-scrollbar,
::v-deep .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}
#pdfContainer::-webkit-scrollbar-thumb,
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 3px;
}

/* 图片样式 */
img {
    object-fit: contain;
    backface-visibility: hidden;
    transition: transform 0.2s ease-in-out !important;
}
</style>
